package server.version;

import server.loader.ServletLoader;
import servlet.HttpServlet;
import servlet.Request;
import servlet.Response;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by louisyuu on 2020/4/2 上午11:03
 * <p>
 * <p>
 * 完成Minicat 3.0版本
 * 需求：可以请求动态资源（Servlet）
 */
public class VersionThreeStarter implements VersionStater {


    @Override
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        new ServletLoader().loadLocalServlet();

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if (ServletLoader.servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                HttpServlet httpServlet = ServletLoader.servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }

            socket.close();

        }
    }
}
